/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

/**
 * 1. Promise 就是一个类，在执行这个类的时候需要传递一个执行器进去，执行器会立即执行
 * 2. Promise 中有三种状态，分别为 成功 fulfilled  失败 rejected   等待 pending
 *      pending -> fulfilled
 *      pending -> rejected
 *      一旦状态确定就不可更改
 * 3. resolve 和 reject 函数是用来更改状态的 
 *      resolve: fulfilled
 *      reject: rejected
 * 4. then 方法内部做的事情就判断状态，如果状态是成功，调用成功的回调函数；如果状态是失败，就调用失败的回调函数；then 方法是定义到原型对象当中
 * 5. then 成功回调有一个参数，表示成功之后的值；失败回调有一个参数，表示失败之后的原因
 * 6. 同一个 promise 对象下面的 then 方法是可以被调用多次的
 * 7. then 方法是可以被链式调用的，后面 then 方法的回调函数拿到的值是上一个 then 方法的回调函数的返回值
 *      判断返回值 x 的值是普通值函数 promise 对象
 *      如果是普通值，直接调用 resolve
 *      如果是 promise 对象，查看 promise 对象返回的结果，再根据 promise 对象返回的结果，决定调用 resolve 还是调用 reject
 */


// 1.代码实现
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e)
        }
    }
    status = PENDING
    value = undefined
    reason = undefined
    sussessCallBack = []
    errorCallBack = []
    resolve = value => {
        if (this.status != PENDING) return;
        this.status = FULFILLED
        this.value = value
        while (this.sussessCallBack.length) this.sussessCallBack.shift()()
    }
    reject = reason => {
        if (this.status != PENDING) return;
        this.status = REJECTED
        this.reason = reason
        while (this.errorCallBack.length) this.errorCallBack.shift()()
    }
    then(sussessCallBack, errorCallBack) {
        sussessCallBack = sussessCallBack ? sussessCallBack : val => val
        errorCallBack = errorCallBack ? errorCallBack : reason => {throw reason}

        let promise2 = new MyPromise((resolve, reject) => {
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let x = sussessCallBack(this.value)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = errorCallBack(this.reason)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0)
            } else {
                this.sussessCallBack.push(() => {
                    setTimeout(() => {
                        try {
                            let x = sussessCallBack(this.value)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0)
                })
                this.errorCallBack.push(() => {
                    setTimeout(() => {
                        try {
                            let x = errorCallBack(this.reason)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0)
                })
            }
        })
        return promise2
    }
    finally (callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value)
        }, reason => {
            return MyPromise.resolve(callback()).then(() => {throw reason})
        })
    }
    catch (error) {
        return this.then(undefined, error)
    }
    static all (array) {
        let result = []
        let index = 0
        return new MyPromise((resolve, reject) => {
            function addData (key, value) {
                result[key] = value
                index++
                if (index === array.length) {
                    return resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                // 判断是普通值还是 promise 对象
                if (array[i] instanceof MyPromise) {
                    // promise 对象
                    array[i].then(val => addData(i, val), reason => {reject(reason)})
                } else {
                    // 普通值
                    addData(i, array[i])
                }
            }
        })
    }
    static resolve (value) {
        //  promise 对象
        if (value instanceof MyPromise) return value
        // 普通值
        return new MyPromise(resolve => resolve(value))
    }
}
function resolvePromise (promise2, x, resolve, reject) {
    if (promise2 === x) {
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        // promise 对象
        x.then(value => {resolve(value)}, reason => {reject(reason)})
    } else {
        // 普通值
        resolve(x)
    }
}

// 2.测试打印
let p1 = new MyPromise((resolve, reject) => {
    // setTimeout(() => {
    //     resolve('成功')
    // }, 3000)
    // throw new Error('executor error')
    // resolve('成功')
    reject('失败')
})

let p2 = function () {
    return new MyPromise((resolve, reject) => {
        setTimeout(() => {
            resolve('p2')
        },2000)
    })
}

p1.then().catch(reason => console.log(reason))

// p1.finally(() => {
//     console.log('finally')
//     return p2()
// }).then(value => console.log(value), reason => console.log(reason))

// MyPromise.resolve(10).then(val => console.log(val))

// p1.then().then().then(val => console.log(val), reason => console.log(reason))

// let p3 = MyPromise.all(['a', 'b', p2(), 'c']).then(value => {console.log(value)}, reason => {console.log(reason)})

// p1.then(value => {
//     // throw new Error('then error')
//     console.log(value)
// }, reason => {
//     console.log(reason)
// }).then(value => {
//     console.log(value)
// }, reason => {
//     console.log(reason)
// })